from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from django.views import generic
from django.db import connection
from django.http import HttpResponse
import json
import datetime

from .models import Account, Postion, OrderRecord
# Create your views here.


def index(request):
    return HttpResponse()


class IndexView(generic.ListView):
    template_name = 'Account/index.html'
    context_object_name = 'ltAccount'

    def get_queryset(self):
        ret = list()
        cursor = connection.cursor()
        for acc in Account.objects.order_by('-money'):
            no_use_money = 0
            for p in Postion.objects.filter(account=acc).all():
                cursor.execute(
                    f"select close from t_stock_day where code='{p.code}' ORDER BY date DESC limit 1; ")
                price = cursor.fetchall()[0][0]
                no_use_money += (p.number * price)
            ret.append({'name': acc.user_name, 'money': acc.money, 'no': no_use_money, 'id': acc.id})

        return ret


def PositionView(request, pk):
    account = get_object_or_404(Account, pk=pk)
    try:
        integer, decimal = str(account.money).split('.')
    except (Exception, ):
        integer = str(account.money)
        decimal = '00'

    sInteger = ""
    counter = 3
    for rPos in range(len(integer)-1, -1, -1):
        sInteger = integer[rPos] + sInteger
        counter -= 1
        if not counter and rPos:
            counter = 3
            sInteger = "," + sInteger

    return render(request, 'Account/pos.html', {
        'ltPosition': account.postion_set.get_queryset(),
        'name': account.user_name, 'money': f"{sInteger}.{decimal}",
        'account_id': account.id
    })


def QueryRecords(request, pk):
    query_result = list()
    account = get_object_or_404(Account, pk=pk)
    for i in account.orderrecord_set.get_queryset():
        query_result.append({
            'code': i.code,
            'price': round(i.price, 2),
            'number': i.number,
            'date': i.date.strftime("%Y/%m/%d %H:%M:%S"),
            'operator': i.operator
        })
    return HttpResponse(json.dumps(query_result), content_type="application/json")


def QueryHasStock(request, code):
    cursor = connection.cursor()
    cursor.execute(f"select name from t_stockinfo where code='{code}';")
    row = cursor.fetchall()
    if row:
        result = {'result': True, 'name': row[0][0]}
        cursor.execute(f"select close from t_stock_day where code='{code}';")
        row = cursor.fetchall()[0]
        result['price'] = row[0]
    else:
        result = {'result': False}
    return HttpResponse(json.dumps(result), content_type="application/json")


def InsertOrder(request):
    account = Account.objects.filter(id=request.POST.get('id')).all()[0]

    cursor = connection.cursor()
    cursor.execute(f"select close from t_stock_day where code='{request.POST.get('code')}' ORDER BY date DESC limit 1; ")
    price = cursor.fetchall()[0][0]
    order = OrderRecord(
        account=account,
        operator=request.POST.get('op'),
        code=request.POST.get('code'),
        number=request.POST.get('num'),
        date=datetime.datetime.now(),
        price=price
    )

    if float(account.money) < float(order.number) * float(order.price):
        return HttpResponse(json.dumps({'code': -1}), content_type="application/json")

    ltPos = account.postion_set.filter(code=request.POST.get('code'))
    if ltPos:
        pos = ltPos[0]
    else:
        pos = Postion(
            account=account,
            code=order.code,
            number=0,
            price=order.price,
        )
    if '买入' in order.operator:
        pos.price = round((float(pos.price)*float(pos.number)+float(order.price)*float(order.number))/(int(pos.number) + int(order.number)), 2)
        pos.number = int(order.number) + int(pos.number)
        account.money = float(account.money) - (float(order.number) * float(order.price))
        pos.save()
    else:  # "卖出" in request.POST.get('op')
        if int(order.number) < int(pos.number) and int(order.number) != -1:
            pos.number = int(pos.number) - int(order.number)
            pos.save()
        else:
            if int(order.number) == -1:
                order.number = pos.number
            pos.delete()
        account.money = (float(order.number) * float(order.price)) + float(account.money)

    account.save()
    order.save()

    return HttpResponse(json.dumps({'code': 0}), content_type="application/json")
